package cn.jinjimi.app.managers;

import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.controller.event.LocalEvent.PlanCompanyChangeEvent;
import cn.jinjimi.app.bean.SharePrefKeys;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by Roy
 * Date: 2017/4/11
 */

public class PlanManager {

    public static class Company {
        public int id;
        public String name;

        public Company(int id, String name) {
            this.id = id;
            this.name = name;
        }
    }

    private static volatile PlanManager instance = null;

    /* 双重检验锁的懒汉模式的单例模式*/
    public static PlanManager getInstance() {
        if (instance == null) {
            synchronized (PlanManager.class) {
                if (instance == null)
                    instance = new PlanManager();
            }
        }
        return instance;
    }

    /**
     * 存储最近一次选择的公司名称和Id
     */
    public void setLastChosenCompany(int id, String name) {
        if (StringUtils.isEmpty(name)) {
            id = 861;
            name = "平安";
        }

        PreferenceManager.setData(SharePrefKeys.PREF_LAST_PLAN_COMPANY_ID, id);
        PreferenceManager.setData(SharePrefKeys.PREF_LAST_PLAN_COMPANY_NAME, name);
        EventBus.getDefault().post(new PlanCompanyChangeEvent());
    }

    /**
     * 获取最近一次选择的公司名称和Id
     */
    public Company getLastChosenCompany() {
        int id = PreferenceManager.getIntData(SharePrefKeys.PREF_LAST_PLAN_COMPANY_ID);
        String name = PreferenceManager.getStringData(SharePrefKeys.PREF_LAST_PLAN_COMPANY_NAME);

        //default value
        if (StringUtils.isEmpty(name)) {
            id = 861;
            name = "平安";
            setLastChosenCompany(id, name);
        }

        return new Company(id, name);
    }
}
